package com.bjpowernode.mvc.exception;

import com.bjpowernode.common.enums.Code;
import com.bjpowernode.mvc.model.response.Response;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    //定义方法处理Bean Validator异常
    @ExceptionHandler(BindException.class)
    public Response doBeanValidator(BindException bindException){

        StringBuffer buffer=new StringBuffer();
        List<FieldError> fieldErrors=bindException.getFieldErrors();   //获取产生的所有bean集合
        fieldErrors.forEach(fieldError -> {
            buffer.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";"); //发送属性.
        });
        Response response=new Response();
        response.setCode(Code.REQUEST_PARAM_ERR.getCode());
        response.setMsg(Code.REQUEST_PARAM_ERR.getMsg()+":"+toString());
        response.setResult("");
        return response;
    }
}
